package dynamic.thread.pool.sdk.registry.redis;

import dynamic.thread.pool.sdk.domain.DynamicThreadPoolService;
import dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import dynamic.thread.pool.sdk.domain.model.valobj.RegistryEnumVO;
import dynamic.thread.pool.sdk.registry.IRegistry;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.List;

/**
 * @author: 奔跑的鑫
 * @description 注册中心 Redis实现类
 * @create 2024-05-12 16:22
 */
public class RedisRegistry implements IRegistry {

    private final RedissonClient redissonClient;
    private final Logger logger = LoggerFactory.getLogger(RedisRegistry.class);

    public RedisRegistry(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public void reportThreadPool(List<ThreadPoolConfigEntity> threadPoolEntities) {
        try {
            // 获取Redis列表的引用
            RList<ThreadPoolConfigEntity> list =
                    redissonClient.getList(RegistryEnumVO.THREAD_POOL_CONFIG_LIST_KEY.getKey());
            // 清空列表中的元素，使用clear()方法而不是delete()
            list.clear();
            // 添加新元素到列表
            list.addAll(threadPoolEntities);
        } catch (Exception e) {
            logger.error("Failed to report thread pool configurations to Redis", e);
            // 根据业务需要，可以选择抛出异常或进行其他恢复操作
            throw new RuntimeException("Failed to update Redis list", e);
        }
    }

    @Override
    public void reportThreadPoolConfigParameter(ThreadPoolConfigEntity threadPoolConfigEntity) {
        String cacheKey = RegistryEnumVO.THREAD_POOL_CONFIG_PARAMETER_LIST_KEY.getKey() + "_" + threadPoolConfigEntity.getAppName() + "_" + threadPoolConfigEntity.getThreadPoolName();
        RBucket<ThreadPoolConfigEntity> bucket = redissonClient.getBucket(cacheKey);
        bucket.set(threadPoolConfigEntity, Duration.ofDays(30));
    }

}
